package com.itheima.tanhua.admin.service;

import com.itheima.commons.utils.CheckCodeUtil;
import com.itheima.commons.utils.Constants;
import com.itheima.commons.utils.JwtUtils;
import com.itheima.dubbo.api.ManagerApi;
import com.itheima.dubbo.api.UserApi;
import com.itheima.model.domain.Manager;
import com.itheima.model.domain.User;
import com.itheima.model.vo.ErrorResult;
import com.itheima.tanhua.admin.exception.BusinessException;
import com.itheima.tanhua.admin.interceptor.ManagerHolder;
import com.itheima.tanhua.admin.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class SystemService {

    @Autowired
    private RedisTemplate redisTemplate;
    @DubboReference(timeout = 1000000000)
    private UserApi userApi;
    @DubboReference(timeout = 1000000000)
    private ManagerApi managerApi;

    public void code(String uuid, HttpServletResponse response) throws IOException {
        //生成验证码
        String verifyImage = CheckCodeUtil.outputVerifyImage(100, 50, response.getOutputStream(), 4);
        //保存验证码的值到redis
        redisTemplate.opsForValue().set(uuid,verifyImage, Duration.ofMinutes(2));

    }

    public Map login(String username, String password, String verificationCode, String uuid) {
        String code = (String)redisTemplate.opsForValue().get(uuid);
        if (!verificationCode.equalsIgnoreCase(code)){//验证码错误
            throw new BusinessException(ErrorResult.codeError());
        }
        redisTemplate.delete(uuid);
        Manager manager = new Manager();
        manager.setUsername(username);
        manager.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        Long uid = managerApi.login(manager);
        if (uid ==null){
            throw new BusinessException(ErrorResult.passwordError());
        }
        //通过jwt生成token
        Map<Object, Object> hashMap = new HashMap<>();
        hashMap.put("uid",uid);
        hashMap.put("username",manager.getUsername());
        String token = JwtUtils.getToken(hashMap);
        //构造返回值
        Map<Object, Object> resMap = new HashMap<>();
        resMap.put("token",token);
        return resMap;
    }

    public void logout() {
        ManagerHolder.remove();
    }

    public Manager find() {
        return managerApi.findById(ManagerHolder.getUid());
    }
}
